package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //1.效验老人是否已入住,如果已入住,直接结束流程
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .in(Elder::getStatus, 4, 1);

        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtil.isNotEmpty(elder)) {
            //已入住
            throw new BaseException("该老人已入住");
        }
        //2.如果没有入住,更新床位状态为已入住
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或更新老人基本信息
        Elder elder1 = insertOrUpdateElder(dto.getCheckInElderDto(),bed);

        //4.新增签约办理
        insertContract(elder1, dto.getCheckInContractDto(),dto.getCheckInConfigDto());

        //5.新增入住信息(家属信息放remark)
        CheckIn checkIn = insertCheckInInfo(bed,elder1,dto);

        //6.新增入住配置
        insertCheckInConfig(checkIn, dto.getCheckInConfigDto());

    }

    @Override
    public CheckInDetailVo detail(Long id) {
        //2.从入住表里获取入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setCheckInId(id);
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        //1.从老人表里获取个人信息
        Long elderId = checkIn.getElderId();
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectById(elderId);

        BeanUtils.copyProperties(elder, checkInElderVo);
        String idCardNo = elder.getIdCardNo();
        //根据身份证获取年龄
        String substring = idCardNo.substring(6, 10);
        checkInElderVo.setAge(LocalDateTime.now().getYear() - Integer.parseInt(substring));

        //3.查询合同
        LambdaQueryWrapper<Contract> contractQueryWrapper = new LambdaQueryWrapper<>();
        contractQueryWrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(contractQueryWrapper);

        //4.查询入住配置
        LambdaQueryWrapper<CheckInConfig> checkInConfigQueryWrapper = new LambdaQueryWrapper<>();
        checkInConfigQueryWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigQueryWrapper);
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        //5.转换家属列表
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = null;
        if (ObjectUtil.isNotEmpty(remark)) {
            elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        }

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        return checkInDetailVo;
    }


    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtil.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckInInfo(Bed bed, Elder elder1, CheckInApplyDto dto) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder1.getId());
        checkIn.setIdCardNo(elder1.getIdCardNo());
        checkIn.setElderName(elder1.getName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(Elder elder1, CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto) {
        Contract contract = new Contract();
        contract.setElderId(Integer.parseInt(String.valueOf(elder1.getId())));
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder1.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        String idCardNo = checkInElderDto.getIdCardNo();
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, idCardNo);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);

        if (ObjectUtil.isNotEmpty(elder)) {
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elder.setStatus(1);
            BeanUtils.copyProperties(checkInElderDto, elder);
            elderMapper.updateById(elder);
            return elder;
        }else{
            Elder elder1 = new Elder();
            BeanUtils.copyProperties(checkInElderDto, elder1);
            elder1.setBedId(bed.getId());
            elder1.setBedNumber(bed.getBedNumber());
            elder1.setStatus(1);
            elderMapper.insert(elder1);
            return elder1;
        }
    }
}
